import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { Spin, Modal, Tag } from 'antd';
import { deviceGroupDetailApi } from '@/api/deviceGraphApi';
import {
  deviceManagerDetailApi,
  deviceManagerReportApi,
  type DeviceItemDetail,
} from '@/api/deviceManagerApi';
import X6Canvas from './modules/X6Canvas';
import RealTimeMonitoring from '@/pages/Device/Manager/modules/tabs/RealTimeMonitoring';
import type { CanvasElement } from './modules/types';
import { useImageColor } from '@/hooks/useImageColor';

/**
 * 组态图预览组件
 * 用于只读模式展示组态图
 */
const GraphView = (props: { id: string }) => {
  let { id } = useParams<{ id: string }>();
  if (props.id) {
    id = props.id;
  }
  const [elements, setElements] = useState<CanvasElement[]>([]);
  const [edges, setEdges] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedElement, setSelectedElement] = useState<CanvasElement | null>(null);
  const [deviceDetail, setDeviceDetail] = useState<DeviceItemDetail | null>(null);
  const [reportData, setReportData] = useState<any>([]);
  const [detailLoading, setDetailLoading] = useState(false);

  const [canvasSize, setCanvasSize] = useState({ width: 1024, height: 980 });
  const [canvasConfig, setCanvasConfig] = useState({
    grid: {
      visible: true,
      type: 'mesh',
      size: 10,
      args: [{ color: '#e5e5e5', thickness: 1 }],
    },
    background: {
      visible: true,
      color: '#ffffff',
      position: 'center',
      repeat: 'repeat',
      size: 'contain',
      backgroundImageEnabled: false,
      image: '',
    },
  });

  // Dynamic background color logic
  const [pageBgColor, setPageBgColor] = useState<string | undefined>(undefined);
  const imageUrl = canvasConfig.background.image;
  const dominantColor = useImageColor(imageUrl || '');

  useEffect(() => {
    if (imageUrl && dominantColor) {
      setPageBgColor(dominantColor);
    } else if (canvasConfig.background.color) {
      setPageBgColor(canvasConfig.background.color);
    } else {
      setPageBgColor(undefined); // Fallback to CSS default
    }
  }, [imageUrl, dominantColor, canvasConfig.background.color]);

  useEffect(() => {
    if (id) {
      loadGraphData(id);
    }
  }, [id]);

  const loadGraphData = async (graphId: string) => {
    try {
      setLoading(true);
      const res = await deviceGroupDetailApi({ id: parseInt(graphId, 10) });
      if (res.success && res.data) {
        if (res.data.content) {
          try {
            const parsedContent = JSON.parse(res.data.content);
            setElements(parsedContent.elements || []);
            setEdges(parsedContent.edges || []);
            if (parsedContent.canvasConfig) {
              setCanvasConfig(parsedContent.canvasConfig);
            }
          } catch (error) {
            console.error('解析组态图内容失败:', error);
            window.$message.error('组态图数据解析失败');
          }
        }
      } else {
        window.$message.error(res.message || '获取组态图失败');
      }
    } catch (error) {
      console.error('获取组态图失败:', error);
      window.$message.error('获取组态图失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const fetchDeviceData = async (deviceId: string, productCode: string, deviceCode: string) => {
      try {
        setDetailLoading(true);
        const detailRes = await deviceManagerDetailApi({ id: Number(deviceId) });
        if (detailRes.success) {
          const deviceData = detailRes.data as DeviceItemDetail;
          deviceData.metaDataJson = JSON.parse(deviceData.metaData || '{}');
          setDeviceDetail(deviceData);

          const reportRes = await deviceManagerReportApi({ productCode, deviceCode });
          if (reportRes.success) {
            setReportData(reportRes.data);
          }
        } else {
          window.$message.error(detailRes.message || '获取设备详情失败');
        }
      } catch (error) {
        console.error('获取设备数据失败:', error);
        window.$message.error('获取设备数据失败');
      } finally {
        setDetailLoading(false);
      }
    };

    if (isModalVisible && selectedElement && selectedElement.properties?.deviceId) {
      const { deviceId, deviceInfo } = selectedElement.properties;
      if (deviceId && deviceInfo?.productCode && deviceInfo?.code) {
        fetchDeviceData(deviceId, deviceInfo.productCode, deviceInfo.code);
      } else {
        console.warn('Device info is incomplete on the selected element.');
      }
    }
  }, [isModalVisible, selectedElement]);

  const handleSelectElement = (element: CanvasElement) => {
    if (element.properties?.deviceId) {
      setSelectedElement(element);
      setIsModalVisible(true);
    }
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    setSelectedElement(null);
    setDeviceDetail(null);
    setReportData([]);
  };

  return (
    <div
      className=" wh-full bg-gray-100 overflow-auto p-4"
      style={{ backgroundColor: pageBgColor }}
    >
      <div style={{ width: canvasSize.width, height: canvasSize.height, margin: '0 auto' }}>
        <X6Canvas
          elements={elements}
          edges={edges}
          scale={1}
          readOnly={true}
          onSelectElement={handleSelectElement}
          onUpdateElement={() => {}}
          onAddElement={() => {}}
          onRemoveElement={() => {}}
          onAddEdge={() => {}}
          onRemoveEdge={() => {}}
          canvasSize={canvasSize}
          gridOptions={canvasConfig.grid}
          backgroundOptions={canvasConfig.background}
        />
      </div>
      <Spin
        spinning={loading}
        className="fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2"
      ></Spin>
      <Modal
        title="设备详情"
        open={isModalVisible}
        onCancel={handleCancel}
        footer={null}
        width={800}
        destroyOnClose
      >
        <Spin spinning={detailLoading}>
          {deviceDetail ? (
            <div>
              <div className="p-4 border-b border-gray-100">
                <div className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-lg p-4 border border-blue-100">
                  <div className="flex items-center justify-between mb-3">
                    <h3 className="text-lg font-semibold text-gray-800">设备信息</h3>
                    <Tag color={deviceDetail.status === 1 ? 'success' : 'error'}>
                      {deviceDetail.status === 1 ? '在线' : '离线'}
                    </Tag>
                  </div>
                  <div className="grid grid-cols-2 gap-x-8 gap-y-3">
                    <div className="flex justify-between items-center">
                      <span className="text-gray-600 text-sm">设备名称:</span>
                      <span className="font-medium text-gray-800">{deviceDetail.deviceName}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-gray-600 text-sm">设备编码:</span>
                      <span className="font-mono text-sm text-gray-700">{deviceDetail.code}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-gray-600 text-sm">产品型号:</span>
                      <span className="text-gray-700">{deviceDetail.productName}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-gray-600 text-sm">最近在线:</span>
                      <span className="text-gray-700 text-xs">
                        {deviceDetail.latestOnlineTime || '未知'}
                      </span>
                    </div>
                    {deviceDetail.address && (
                      <div className="flex justify-between items-center col-span-2">
                        <span className="text-gray-600 text-sm">位置信息:</span>
                        <span
                          className="text-gray-700 text-xs max-w-xs truncate"
                          title={deviceDetail.address}
                        >
                          {deviceDetail.address}
                        </span>
                      </div>
                    )}
                  </div>
                </div>
              </div>
              <div className="p-4">
                <RealTimeMonitoring
                  deviceDetail={deviceDetail}
                  reportData={reportData}
                  type="col"
                  reportLoading={false}
                  onSwitchToPropertyRecords={() => {}}
                  onSwitchToServiceRecords={() => {}}
                />
              </div>
            </div>
          ) : (
            <div style={{ height: '400px' }} />
          )}
        </Spin>
      </Modal>
    </div>
  );
};

export default GraphView;
